package tristate
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Image;

	[Event (name="change", type="flash.events.Event")]
	public class TristateControl extends Image
	{
        [Embed(source="/tristate/resources/unchecked.png")]
        private var imgUnchecked:Class;

        [Embed(source="/tristate/resources/checked.png")]
        private var imgChecked:Class;

        [Embed(source="/tristate/resources/circled.png")]
        private var imgCircled:Class;
		
		private var m_state:TsState = TsState.Unchecked;

		[Bindable]
		public function get state():TsState
		{
			return  m_state;
		}	

		public function set state(newState:TsState):void
		{
			if(m_state != newState)
			{
				m_state = newState;
				switch(newState)
				{
					case TsState.Checked:
						load(imgChecked);
						//invalidateDisplayList();
						break;
					case TsState.Circled:
						load(imgCircled);
						//invalidateDisplayList();
						break;
					case TsState.Unchecked:
						load(imgUnchecked);
						//invalidateDisplayList();
						break;
				}
			}
		}

		public function TristateControl()
		{
			super();
			addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
			load(imgUnchecked);
			m_state = TsState.Unchecked
		}
		
		private function onClick(evt:MouseEvent):void
		{
			if (super.enabled) {
				switch(m_state)
				{
					case TsState.Checked:
						state = TsState.Circled;
						break;
					case TsState.Circled:
						state = TsState.Unchecked;
						break;
					case TsState.Unchecked:
						state = TsState.Checked;
						break;
				}
				var eventObj:Event = new Event(Event.CHANGE);
				dispatchEvent(eventObj);
			}		
		}
	}
}